import { defineStore } from 'pinia'
import { computed, reactive } from 'vue'

export const use_global_state = defineStore('global/state', () => {
    const state = reactive<{ allow_close_window: boolean }>({ allow_close_window: true })
    const allow_close_window = computed(() => state.allow_close_window)

    const set_allow_close_window = (allow_close_window: boolean) => {
        state.allow_close_window = allow_close_window
    }

    return { allow_close_window, set_allow_close_window }
})

export const use_ui_setting = defineStore('setting/ui', () => {
    const state = reactive<{ send_mode: string; default_command: string; default_search_engine: string }>({ send_mode: 'Enter', default_command: 'ai', default_search_engine: 'Google' })

    const initialize = () => {
        {
            state.send_mode = 'Enter'
            const value = localStorage.getItem('setting:ui:send_mode')
            if ('string' === typeof value) {
                state.send_mode = value
            }
        }

        {
            state.default_command = 'ai'
            const value = localStorage.getItem('setting:ui:default_command')
            if ('string' === typeof value) {
                state.default_command = value
            }
        }

        {
            state.default_search_engine = 'Google'
            const value = localStorage.getItem('setting:ui:default_search_engine')
            if ('string' === typeof value) {
                state.default_search_engine = value
            }
        }
    }

    const send_mode = computed(() => state.send_mode)
    const set_send_mode = (send_mode: string) => {
        state.send_mode = send_mode
        localStorage.setItem('setting:ui:send_mode', send_mode)
    }

    const default_command = computed(() => state.default_command)
    const set_default_command = (default_command: string) => {
        state.default_command = default_command
        localStorage.setItem('setting:ui:default_command', default_command)
    }

    const default_search_engine = computed(() => state.default_search_engine)
    const set_default_search_engine = (default_search_engine: string) => {
        state.default_search_engine = default_search_engine
        localStorage.setItem('setting:ui:default_search_engine', default_search_engine)
    }

    return { initialize, send_mode, set_send_mode, default_command, set_default_command, default_search_engine, set_default_search_engine }
})
